package com.haoxin.ai_course.interceptor;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.haoxin.ai_course.common.annotation.AuthIgnore;
import com.haoxin.ai_course.common.exception.RRException;
import com.haoxin.ai_course.modules.sys.entity.SysUser;
import com.haoxin.ai_course.modules.sys.entity.SysUserToken;
import com.haoxin.ai_course.modules.sys.service.ShiroService;

/**
 * 权限(Token)验证
 * 
 * @author czx
 * @email object_czx@163.com
 * @date 2017-03-23 15:38
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private ShiroService shiroService;

	public static final String USER_KEY = "userId";
	public static final String TOKEN = "token";
	public boolean isDeubg = true;
	private Set<String> excludeUrl = new HashSet<>();

	public Set<String> getExcludeUrl() {
		excludeUrl.add("/doc.html");
		excludeUrl.add("/sys/login");
		excludeUrl.add("/actuator/**");
		excludeUrl.add("/app/**");
		excludeUrl.add("/sys/login");
		excludeUrl.add("/sys/unauthorized");
		excludeUrl.add("/sys/code/**");
		excludeUrl.add("/mobile/code/**");
		excludeUrl.add("/mobile/login/**");
		excludeUrl.add("/v2/**");
		excludeUrl.add("/");
		excludeUrl.add("/doc.html");
		excludeUrl.add("/follow-api/doc.html");
		excludeUrl.add("/miniProgram/doctorinfo/getUserInfoByWechat");
		excludeUrl.add("/**");
		excludeUrl.add("/auth/**");
		excludeUrl.add("/sys/gen/**");
		return excludeUrl;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		AuthIgnore annotation;
		String url = request.getRequestURI();
		Set<String> urlSet = this.getExcludeUrl();
		for (String str : urlSet) {
			if (url.contains(str)) {
				return true;
			}
		}
//        
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthIgnore.class);
		} else {
			return true;
		}

		if (annotation != null) {
			return true;
		}

		// 获取用户凭证
		String token = request.getHeader(TOKEN);
		if (StringUtils.isBlank(token)) {
			token = request.getParameter(TOKEN);
		}

		// 凭证为空
		if (StringUtils.isBlank(token)) {
			throw new RRException(TOKEN + "不能为空", HttpStatus.UNAUTHORIZED.value());
		}

		// 根据accessToken，查询用户信息
		SysUserToken tokenEntity = shiroService.queryByToken(token);
		// token失效
		if (tokenEntity == null ) {
			throw new RRException( "失效002，token为空，请重新登录", HttpStatus.UNAUTHORIZED.value());
		}
		if (tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
			throw new RRException( "失效003，token已过期，请重新登录", HttpStatus.UNAUTHORIZED.value());
		}
		SysUser user = shiroService.queryUser(tokenEntity.getUserId());
		if(user == null) {
			throw new RRException( "失效004，token无效，用户不存在", HttpStatus.UNAUTHORIZED.value());
		}
		// 设置userId到request里，后续根据userId，获取用户信息
		request.setAttribute(USER_KEY, user.getUserId());

		return true;
	}
}
